#include "stdafx.h"
#include <LitCacheManager.h>

#ifdef LIT_OGRE_SUPPORT
#include <OgreImage.h>
#endif

#ifdef LIT_BOOST_SUPPORT
#include <LitFileSystem.h>
#endif

namespace Lit
{
	CacheManager::CacheManager() : CoreComponent(){}
	CacheManager::~CacheManager(){}
	
	bool CacheManager::isFileCached( const String &name, CacheLocation loc, const String &subdir ) const
	{
		return getCachePath(name,loc,subdir).exists();
	}

#ifdef LIT_OGRE_SUPPORT
	Ogre::Image CacheManager::getCachedImage( const String &name, CacheLocation loc, const String &subdir ) const{
		FilePath path(getCachePath(name, loc, subdir));
		if( !isFileCached( name, loc, subdir ) )
			throw Lit::FileMissing( "Cached Image '"+path+"'", EXC_LOC );

		FILE *f=NULL;
		if( fopen_s(&f, path.str().c_str(), "rb") != ERROR_SUCCESS )
			throw FileMissing( path.str(), EXC_LOC );
		Ogre::DataStreamPtr stream(new Ogre::FileHandleDataStream( path, f, Ogre::DataStream::READ ));
		Ogre::Image ret;
		ret.load( stream );

		stream->close();
		stream.setNull();
		return ret;
	}
#endif
	FilePath CacheManager::getCachePath( const String &name, CacheLocation loc, const String &subdir ) const{
		return getLocationPath(loc, subdir)+name;
	}
	RefPtr<FileStream> CacheManager::createCachedResource( const String &name, bool binary, CacheLocation loc, const String &subdir ) const
	{
		String path = getCachePath( name, loc, subdir );
		return new FileStream(path, binary?Stream::BinaryWrite:Stream::TextWrite);
	}
	RefPtr<FileStream> CacheManager::openCachedResource( const String &name, bool binary, CacheLocation loc, const String &subdir ) const
	{
		String path = getCachePath( name, loc, subdir );
		if( !isFileCached( name, loc, subdir ) )
			throw InvalidPath( path, false, EXC_LOC );
		return new FileStream(path, binary?Stream::BinaryRead:Stream::TextRead);
	}
	FilePath CacheManager::getLocationPath( CacheLocation loc, const String &subdir ) const
	{
		String path(mBasePath);
		switch( loc )
		{
		case CL_ROOT:path+="/";break;
		case CL_TMP:
		case CL_PRE_RENDER: 
			path+=String(trCacheLocation( loc ))+"/"; break;
		default:
			break;
		};
		path += subdir.empty()?"":(subdir + "/");
		FilePath p(path);
		p.make();
		return p;
	}
#ifdef LIT_OGRE_SUPPORT
	void CacheManager::initialise( const OgreDetails &details ){
#else
	void CacheManager::initialise( ){
#endif
		mBasePath = Lit::FileSystem::applicationPath() + "/cache/";
	}
	void CacheManager::shutdown(){
	}
};